<template>
  <div class="container">
    <div class="header">生产不良相关</div>
    <div class="echart-container">
      <div ref="echartsBox" class="echarts-box"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import commomOption from './commomOption.ts'
import * as echarts from 'echarts'

const option = {
  tooltip: commomOption.tooltip,
  grid: commomOption.grid,
  xAxis: Object.assign({}, commomOption.xAxis, {
    data: ['1月', '2月', '3月', '4月', '5月'],
  }),
  yAxis: Object.assign({}, commomOption.yAxis, {
    axisLabel: {
      color: 'rgb(255, 255, 255)',
      formatter: '{value}%', //y轴数值，带百分号
    },
    min: 0,   //最小百分比
    max: 100, //最大百分比
  }),
  series: [
    {
      name: '不良率',
      emphasis: {
        focus: 'series',
      },
      type: 'pictorialBar',
      barCategoryGap: '10%' /*多个并排柱子设置柱子之间的间距*/,
      symbol: 'path://M0,10 L10,10 C5.5,10 5.5,5 5,0 C4.5,5 4.5,10 0,10 z',
      itemStyle: {
        color: function (params) {
          var colorList = [createLinearGradient('rgba(242,167,67, 1)', 'rgba(242,167,67, 0.1)'),
          createLinearGradient('rgba(1,254,246,1)', 'rgba(1,254,246,0.1)'),
          createLinearGradient('rgba(65,89,245,1)', 'rgba(65,89,245,0.1)'),
          createLinearGradient('rgba(51,204,255,1)', 'rgba(51,204,255,0.1)'),
          createLinearGradient('rgba(16,127,198,1)', 'rgba(16,127,198,0.1)'),
            '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae']
          return colorList[params.dataIndex]
        }
      },
      data: [60, 30, 40, 49, 35],
    }
  ],
}

function createLinearGradient(colorStart, colorEnd) {
  if (!colorEnd) {
    colorEnd = convertToRGBA(colorStart, 0.1)
  }
  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: colorStart },
    { offset: 0.4, color: colorStart },
    { offset: 1, color: colorEnd },
  ])

  // 转换颜色值为 rgba 字符串
  function convertToRGBA(color, opacity) {
    var hexRegExp = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
    var result = hexRegExp.exec(color)
    var r = parseInt(result[1], 16)
    var g = parseInt(result[2], 16)
    var b = parseInt(result[3], 16)
    return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'
  }
}

const { proxy } = getCurrentInstance()
const echartsBox = ref()
function echartInit() {
  nextTick(() => {
    let myChart = proxy.$echarts.init(echartsBox.value)

    option && myChart.setOption(option)
    window.addEventListener('resize', function () {
      myChart.resize()
    })
  })
}
echartInit()
</script>
<style lang="less" scoped>
@import url(./container.less);
</style>
